import { createRouter, createWebHistory } from "vue-router";
import { fetchUserInfo } from "@/state/user";
import LoginView from "@/views/LoginView.vue";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "default",
      redirect: () => {
        return { path: "/overview" };
      }
    },
    {
      path: "/login",
      name: "login",
      meta: {
        requireAuth: false,
        title: "登录"
      },
      component: LoginView
    },
    {
      path: "/overview",
      name: "overview",
      meta: {
        requireAuth: true,
        title: "概览"
      },
      component: () => import("../views/OverviewView.vue")
    },
    {
      path: "/devices",
      name: "devices",
      meta: {
        requireAuth: true,
        title: "设备"
      },
      component: () => import("../views/DevicesView.vue")
    },
    {
      path: "/settings",
      name: "settings",
      meta: {
        requireAuth: true,
        title: "设置"
      },
      component: () => import("../views/SettingsView.vue")
    },
    {
      path: "/about",
      name: "about",
      meta: {
        requireAuth: true,
        title: "关于"
      },
      component: () => import("../views/AboutView.vue")
    },
    {
      path: "/statistics",
      name: "statistics",
      meta: {
        requireAuth: true,
        title: "统计"
      },
      component: () => import("../views/StatisticsView.vue")
    },
    {
      path: "/region",
      name: "region",
      meta: {
        requireAuth: true,
        title: "区域"
      },
      component: () => import("../views/RegionView.vue")
    },
    {
      path: "/details",
      name: "details",
      meta: {
        requireAuth: true,
        title: "详情"
      },
      component: () => import("../views/DetailsView.vue")
    },
    {
      path: "/account",
      name: "account",
      meta: {
        requireAuth: true,
        title: "帐号"
      },
      component: () => import("../views/AccountView.vue")
    }
  ]
});

if (import.meta.env.DEV) {
  router.addRoute({
    path: "/test",
    name: "test",
    meta: {
      requireAuth: true,
      title: "测试"
    },
    component: () => import("../views/TestView.vue")
  });
}

router.beforeEach(async to => {
  if (to.meta?.requireAuth && !fetchUserInfo()) {
    return { name: "login" };
  } else if (to.name == "login" && fetchUserInfo()) {
    return { name: "default" };
  }
});

router.afterEach(async to => {
  const title = to.meta?.title;
  if (title != null) {
    document.title = `网络扫描检测系统 - ${title}`;
  } else {
    document.title = "网络扫描检测系统";
  }
});

export default router;
